#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :add_month_report_table_page.py
# Time  :2025/4/24 16:11
# Email :fortunatedong@163.com
# Author:by Adonli
# from datetime import datetime
#
# import pandas as pd
# import streamlit as st
# from config import Header_space
# from settings.report_table import load_report_table
#
# Header_space()
# st.subheader("月报总结", divider=True)
# report_table_detail = load_report_table()
# today = datetime.today()
# current_year = today.year
# current_month = today.month
# col1, col2, col3, col4, col5, col6 = st.columns(6)
# with col1:
#     start_date = st.date_input(":blossom:**开始日期**",format="YYYY-MM-DD")
#     # st.write("Your birthday is:", d)
# with col2:
#     end_date = st.date_input(":blossom:**结束日期**",format="YYYY-MM-DD")
#     # st.write("Your birthday is:", d)
# with col3:
#     author = st.text_input(":blossom:**汇报人**")
#     # st.write("Your birthday is:", d)
# with col4:
#     department_option = ("项目开发部门", "研发部门", "运营部门", "电商部门", "终端事业部门", "财务部门")
#     department = st.selectbox(":blossom:**部门**",department_option,index=None,placeholder="选择部门")
#     # st.write("Your birthday is:", d)
# with col5:
#     type = ("日报", "月报", "半年报", "年报")
#     report_type = st.selectbox(":blossom:**报表类型**",type,index=None,placeholder="选择类型")
#     # st.write("Your birthday is:", d)
# with col6:
#     col6_col1, col6_col2, col6_col3 = st.columns(3)
#     with col6_col1:
#         st.write("")
#         search_button = st.button("**搜索**")
#     with col6_col2:
#         st.write("")
#         update_button = st.button("**修改**")
#     with col6_col3:
#         st.write("")
#         add_button = st.button("**新增**")
# st.divider()
# report_table  = []
# for row in report_table_detail:
#     DATE = row["DATE"]
#     AUTHOR = row["AUTHOR"]
#     DEPARTMENT = row["DEPARTMENT"]
#     REPORTTYPE = row["REPORTTYPE"]
#     LOOK = f"month_report_table_page?date={row["DATE"]}"
#     report_table.append({"日期":DATE,"汇报人":AUTHOR,"部门":DEPARTMENT,"月报类型":REPORTTYPE,"报告详情":LOOK})
# st.data_editor(
#     report_table,
#     column_config={
#         "报告详情": st.column_config.LinkColumn(
#             "报告详情",
#             display_text="查看报告",
#             help="点击查看报告详情",
#             validate=None
#         )
#     },
#     hide_index=True,
#     disabled=True  # 如果只是展示不需要编辑
# )
import time

import streamlit as st
import pandas as pd
import json
from datetime import datetime
from config import ROOT_DIR, Header_space
from settings.report_table import load_report_table, save_report_table

Header_space()
st.subheader("月报总结", divider=True)

def init_report_table():
    return load_report_table()


def sort_by_date_desc(data):
    """按照DATE字段降序排序"""
    return sorted(data, key=lambda x: datetime.strptime(x["DATE"], "%Y-%m"), reverse=True)

def is_main_info_duplicate(date, author, department, exclude_index=None):
    """检查主信息是否重复"""
    for i, item in enumerate(st.session_state.report_table_detail):
        if exclude_index is not None and i == exclude_index:
            continue
        if (item["DATE"] == date):
            return True
    return False
def main():


    # 初始化数据
    if 'report_table_detail' not in st.session_state:
        st.session_state.report_table_detail = init_report_table()

    # 获取所有主信息用于选择
    def get_main_info_list():
        main_info_list = []
        seen = set()
        for item in sort_by_date_desc(st.session_state.report_table_detail):
            key = (item["DATE"], item["AUTHOR"], item["DEPARTMENT"], item["REPORTTYPE"])
            if key not in seen:
                seen.add(key)
                main_info_list.append({
                    "DATE": item["DATE"],
                    "AUTHOR": item["AUTHOR"],
                    "DEPARTMENT": item["DEPARTMENT"],
                    "REPORTTYPE": item["REPORTTYPE"]
                })
        return main_info_list

    # 主信息管理区域
    st.html(
        '<p style="font-family:arial;color:blue;font-size:20px;">主信息管理</p>'
    )
    # 选择要编辑的主记录或创建新记录
    main_info_list = get_main_info_list()
    # st.write(main_info_list)
    main_options = [f"{item['DATE']} - {item['AUTHOR']} - {item['DEPARTMENT']}" for item in main_info_list]
    main_options.insert(0, "新建主信息")

    selected_main = st.selectbox(
        "选择要编辑的报表或创建新报表",
        options=main_options,
        key="main_selector"
    )

    # 主信息编辑表单
    with st.form("main_info_form"):
        if selected_main == "新建主信息":
            date = st.text_input("日期*", value=datetime.now().strftime("%Y-%m"), key="new_date")
            author = st.text_input("作者*", value="", key="new_author")
            department = st.text_input("部门*", value="", key="new_dept")
            report_type = st.selectbox(
                "报表类型*",
                options=["日报", "月报", "半年报", "年报"],
                index=1,
                key="new_type"
            )
            is_new = True
            original_main = None
        else:
            selected_index = main_options.index(selected_main) - 1
            current_main = main_info_list[selected_index]
            date = st.text_input("日期*", value=current_main["DATE"], key="date_input")
            author = st.text_input("作者*", value=current_main["AUTHOR"], key="author_input")
            department = st.text_input("部门*", value=current_main["DEPARTMENT"], key="dept_input")
            report_type = st.selectbox(
                "报表类型*",
                options=["日报", "月报", "半年报", "年报"],
                index=["日报", "月报", "半年报", "年报"].index(current_main["REPORTTYPE"]),
                key="type_input"
            )
            is_new = False
            original_main = current_main

        col1, col2, col3 = st.columns(3)
        with col1:
            save_main = st.form_submit_button("保存主信息")
        with col2:
            if not is_new:
                delete_main = st.form_submit_button("删除主信息")

        if save_main:
            if not all([date, author, department, report_type]):
                st.error("请填写所有带*的必填项")
            else:
                # 检查是否重复
                if is_new:
                    if is_main_info_duplicate(date, author, department):
                        st.error("已存在相同日期、作者和部门的主信息，请修改后重试")
                    else:
                        # 添加新主信息
                        new_main = {
                            "DATE": date,
                            "AUTHOR": author,
                            "DEPARTMENT": department,
                            "REPORTTYPE": report_type,
                            "REPORTDETAIL": []
                        }
                        st.session_state.report_table_detail.append(new_main)
                        save_report_table(sort_by_date_desc(st.session_state.report_table_detail))
                        st.success("主信息保存成功！")
                        st.rerun()
                else:
                    # 检查修改后的信息是否与其他记录重复
                    if (date != original_main["DATE"] or
                            author != original_main["AUTHOR"] or
                            department != original_main["DEPARTMENT"]):
                        if is_main_info_duplicate(date, author, department):
                            st.error("修改后的主信息与已有记录重复，请修改后重试")
                            return

                    # 更新现有主信息
                    for item in st.session_state.report_table_detail:
                        if (item["DATE"] == original_main["DATE"] and
                                item["AUTHOR"] == original_main["AUTHOR"] and
                                item["DEPARTMENT"] == original_main["DEPARTMENT"]):
                            item["DATE"] = date
                            item["AUTHOR"] = author
                            item["DEPARTMENT"] = department
                            item["REPORTTYPE"] = report_type

                    save_report_table(sort_by_date_desc(st.session_state.report_table_detail))
                    st.success("主信息保存成功！")
                    st.rerun()

        if not is_new and 'delete_main' in locals() and delete_main:
            # 删除主信息及关联的权限信息
            old_main = main_info_list[selected_index]
            st.session_state.report_table_detail = [
                item for item in st.session_state.report_table_detail
                if not (item["DATE"] == old_main["DATE"] and
                        item["AUTHOR"] == old_main["AUTHOR"] and
                        item["DEPARTMENT"] == old_main["DEPARTMENT"])
            ]
            save_report_table(sort_by_date_desc(st.session_state.report_table_detail))
            st.success("主信息及关联权限信息已删除！")
            st.rerun()

    # 权限信息管理区域（仅当选择了具体主信息时显示）
    if selected_main != "新建主信息" and main_options.index(selected_main) > 0:
        st.header("修改报告")

        # 获取当前主记录
        selected_index = main_options.index(selected_main) - 1
        current_main = main_info_list[selected_index]
        # st.write(f"current_main:{current_main}")

        # 获取当前主记录的所有权限页
        current_report_detail_pages = []
        for item in st.session_state.report_table_detail:
            if (item["DATE"] == current_main["DATE"] and
                    item["AUTHOR"] == current_main["AUTHOR"] and
                    item["DEPARTMENT"] == current_main["DEPARTMENT"]):
                current_report_detail_pages = item["REPORTDETAIL"]
                break
        # st.write(f"current_report_detail_pages:{current_report_detail_pages}")
        # 转换为DataFrame
        report_detail_df = pd.DataFrame(current_report_detail_pages if current_report_detail_pages else [{
            "department": "",
            "type": "",
            "detail": "",
            "finsh": "未开始",
            "effects": "",
            "work_hour": 0.0,
            "workload": ""
        }])
        # st.write(f"report_detail_df:{report_detail_df}")
        # 权限页编辑器
        edited_report_detail_df = st.data_editor(
            report_detail_df,
            num_rows="dynamic",
            column_config={
                "department": st.column_config.TextColumn("权限部门*", required=True),
                "type": st.column_config.TextColumn("类型*", required=True),
                "detail": st.column_config.TextColumn("详情*", required=True),
                "finsh": st.column_config.SelectboxColumn(
                    "完成状态*",
                    options=["已完成", "进行中", "未开始","已终止"],
                    required=True
                ),
                "effects": st.column_config.TextColumn("效果", required=False),
                "work_hour": st.column_config.NumberColumn("工时/月", format="%.1f", required=False),
                "workload": st.column_config.TextColumn("节省工作量", required=False),
            },
            hide_index=True,
            key="report_detail_editor"
        )

        # 保存权限信息
        if st.button("保存权限信息"):
            # 验证必填字段
            required_cols = ["department", "type", "detail", "finsh"]
            for _, row in edited_report_detail_df.iterrows():
                if any(pd.isna(row[col]) or row[col] == "" for col in required_cols):
                    st.error("请填写所有带*的必填项")
                    time.sleep(3)
                    st.stop()

            # 更新权限页数据
            for item in st.session_state.report_table_detail:
                if (item["DATE"] == current_main["DATE"] and
                        item["AUTHOR"] == current_main["AUTHOR"] and
                        item["DEPARTMENT"] == current_main["DEPARTMENT"]):
                    item["REPORTDETAIL"] = edited_report_detail_df.to_dict('records')
                    # st.write(item["REPORTDETAIL"])
                    break

            save_report_table(sort_by_date_desc(st.session_state.report_table_detail))
            st.success("报告信息保存成功！")
            time.sleep(3)
            st.rerun()

    # 显示当前JSON数据
    # st.header("当前数据预览")
    # st.json(sort_by_date_desc(st.session_state.report_table_detail))

    # 提供下载按钮
    st.download_button(
        label="下载JSON文件",
        data=json.dumps(sort_by_date_desc(st.session_state.report_table_detail), ensure_ascii=False, indent=2),
        file_name="report_table_detail.json",
        mime="application/json"
    )


if __name__ == "__main__":
    main()